import { AssetLoader } from "./AssetLoader";
import * as cc from 'cc';

declare let CC_EDITOR;
declare global {
    type Constructor<T = unknown> = new (...args: any[]) => T;
}

export class LoaderMgr {
    readonly KEY_UI = "UI";
    readonly KEY_SHARE = "share";
    readonly KEY_SPINE = "spine";
    private loaders: Map<any, AssetLoader> = new Map();
    public get share(): AssetLoader {
        return AssetLoader.getInstance();
    }


    // 一个简单的池
    private pool = new Array<AssetLoader>();
    private _getLoader() {
        if (this.pool.length) {
            return this.pool.pop();
        }
        return new AssetLoader();
    }
    private _putLoader(loader: AssetLoader) {
        this.pool.push(loader);
    }


    /**
     * 可以从外部传入自定义的 loader
     * @param key 
     * @param loader 
     */
    public set(key: any, loader: AssetLoader) {
        if (key === this.KEY_SHARE) {
            console.warn(`LoaderMgr-> 不能对 share loader 进行替换`);
            return;
        }
        if (typeof key !== 'string') {
            key = cc.js.getClassName(key);
        }
        if (this.loaders.has(key)) {
            console.warn(`LoaderMgr-> 已经存在同名 Loader`);
        }
        this.loaders.set(key, loader);
    }

    /**
     * 获取 loader ，如果不存在则创建一个
     * @param key 
     * @returns 
     */
    public get(key: any): AssetLoader {
        if (CC_EDITOR) {
            return;
        }
        if(!key){
            key = this.KEY_SHARE;
        }
        // if (typeof key !== 'string') {
        //     key = cc.js.getClassName(key);
        // }

        if (key === this.KEY_SHARE) {
            return this.share;
        }
        if (this.loaders.has(key)) {
            return this.loaders.get(key);
        }

        let loader = this._getLoader()
        this.loaders.set(key, loader);
        return loader;
    }

    /**
     * 释放 loader 中所有的资源，并将 loader 放入到池
     * @param key 
     */
    public releaseLoader(key: any) {
        // if (typeof key !== 'string') {
        //     key = cc.js.getClassName(key);
        // }
        if(!key){
            key = this.KEY_SHARE;
        }
        // share 只进行资源释放
        if(key === this.KEY_SHARE){
            this.share.releaseAll();
            return;
        }

        if(this.loaders.has(key)){
            let loader: AssetLoader = this.loaders.get(key);
            loader.releaseAll();
            this.loaders.delete(key);
            this._putLoader(loader);
        } else {
            cc.log(`LoaderMgr-> [ ${key} ] 不存在！`);
        }
    }


    private static _instance: LoaderMgr = null
    public static getInstance(): LoaderMgr {
        if (!this._instance) {
            this._instance = new LoaderMgr();
        }
        return this._instance;
    }
}

export let loaderMgr = LoaderMgr.getInstance();